package cn.echoedu.control;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.echoedu.command.base.FailureParam;
import cn.echoedu.command.base.SuccessParam;
import cn.echoedu.constants.Role;
import cn.echoedu.entity.Department;
import cn.echoedu.entity.Image;
import cn.echoedu.entity.ReceiveSchoolNotify;
import cn.echoedu.entity.SchoolNotify;
import cn.echoedu.entity.SchoolNotifyImage;
import cn.echoedu.entity.Teacher;
import cn.echoedu.entity.receivecommand.DeleteSchoolNotifyReceive;
import cn.echoedu.entity.receivecommand.SchoolNotifyFirstReceive;
import cn.echoedu.entity.receivecommand.SchoolNotifyListDetailReceive;
import cn.echoedu.entity.receivecommand.SchoolNotifyListReceive;
import cn.echoedu.entity.receivecommand.TeacherAddNotifyReceive;
import cn.echoedu.entity.receivecommand.TeacherAddNotifyReceive.PicUrl64;
import cn.echoedu.util.DateUtil;
import cn.echoedu.util.DigitUtil;
import cn.echoedu.util.ImageUtil;
import cn.echoedu.util.L;
import cn.echoedu.util.ObjectUtil;
import cn.echoedu.util.RandomUtil;

public class SchoolNotifyControl extends BaseControl{
	private final int ADD_NOTIFY_ERROR = -1;
	private final String T = "AddSchoolNotifyControl------------->>";


	private void sendSuccess(HttpServletRequest request,HttpServletResponse response,
			Object param,String token,int code){
		SuccessParam successparam = new SuccessParam();
		successparam.setParam(param);
		successparam.setRequest(request);
		successparam.setResponse(response);
		successparam.setToken(token);
		successparam.setCode(code);
		getResponseService().doTeacherAddNotifySuccess(successparam);
	}
	private void sendFailure(HttpServletRequest request,
			HttpServletResponse response,Object param){
		FailureParam failureparam = new FailureParam();
		failureparam.setParam(param);
		failureparam.setRequest(request);
		failureparam.setResponse(response);
		getResponseService().doTeacherAddNotifyFailure(failureparam);
	}
	public void addSchoolNotify(HttpServletRequest request,
			HttpServletResponse response,TeacherAddNotifyReceive teacheraddnotifyreceive) {
		// TODO Auto-generated method stub
		final String M = "addSchoolNotify********>>";
		pL(M);
		//		getNumOfNotify(teacheraddnotifyreceive);
		int notifykey = addNotify(teacheraddnotifyreceive);
		if(ADD_NOTIFY_ERROR==notifykey){
			pL(M);
			sendFailure(request,response,teacheraddnotifyreceive.getCode());
			return;
		}
		if(!"0".equals(teacheraddnotifyreceive.getIsdefault())&&!addReceiveList(teacheraddnotifyreceive,notifykey)){
			L.p(T+M+"add receive list error");
			sendFailure(request,response,teacheraddnotifyreceive.getCode());
			return;
		}
		L.p(T+M+"success");
		sendSuccess(request,response,"",teacheraddnotifyreceive.getToken(),
				teacheraddnotifyreceive.getCode());

	}
	private int getMaxIdOfNotifyOfDepartment(
			TeacherAddNotifyReceive teacheraddnotifyreceive) {
		// TODO Auto-generated method stub
		return getSchoolNotifyModel().getMaxIdOfNotifyOfDepartment(teacheraddnotifyreceive);
	}
	private int getMaxIdOfNotify(
			TeacherAddNotifyReceive teacheraddnotifyreceive) {
		// TODO Auto-generated method stub
		return getSchoolNotifyModel().getMaxIdOfNotify(teacheraddnotifyreceive);
	}
	private boolean addReceiveList(
			TeacherAddNotifyReceive teacheraddnotifyreceive,int notifykey) {
		// TODO Auto-generated method stub
		final String M = "addReceiveList********>>";
		pL(M);
		if(isDefault(teacheraddnotifyreceive)){
			return addSchoolNotifyDefault(teacheraddnotifyreceive,notifykey);
		}else{
			return whenIsNotDefault(teacheraddnotifyreceive,notifykey);
		}

	}
	private boolean addSchoolNotifyDefault(
			TeacherAddNotifyReceive teacheraddnotifyreceive,int notifykey) {
		// TODO Auto-generated method stub
		final String M = "addSchoolNotifyDefault***********>>";
		pL(M);
		return  getReceiveSchoolNotifyModel().putInfoWhenDefault(teacheraddnotifyreceive,notifykey);

	}
	private boolean whenIsNotDefault(
			TeacherAddNotifyReceive teacheraddnotifyreceive,int primarykey) {
		// TODO Auto-generated method stub
		final String M  = "whenIsNotDefault********>>";
		pL(M);
		return addReceivePeople(teacheraddnotifyreceive,primarykey);
	}


	private boolean addReceivePeople(
			TeacherAddNotifyReceive teacheraddnotifyreceive,int primarykey) {
		// TODO Auto-generated method stub
		final String M  = "addReceivePeople*********>>";
		pL(M);

		return getReceiveSchoolNotifyModel().putInfoWhenIsNotDefault(teacheraddnotifyreceive
				,primarykey);
	}
	private boolean isDefault(TeacherAddNotifyReceive teacheraddnotifyreceive) {
		// TODO Auto-generated method stub
		final String M  = "isDefault***********>>";
		pL(M);
		return "0".equals(teacheraddnotifyreceive.getIsdefault())?true:false;
	}
	private int addNotify(TeacherAddNotifyReceive teacheraddnotifyreceive){
		final String M  = "addNotify*******>>";
		pL(M);
		int schoolnotifykey = ADD_NOTIFY_ERROR;
		List<String> imageurllist = generateImage(teacheraddnotifyreceive);
		if(imageurllist==null||imageurllist.size()<=0){
			return ADD_NOTIFY_ERROR;
		}
		schoolnotifykey = addNotifyContent(teacheraddnotifyreceive);
		if(schoolnotifykey==ADD_NOTIFY_ERROR){
			deleteNotifyContent(schoolnotifykey);
			return ADD_NOTIFY_ERROR;
		}
		List<Integer> imagelist = addNotifyImage(teacheraddnotifyreceive,imageurllist);
		L.p(T+M+"imagelist:"+imagelist);
		if(imagelist==null||imagelist.size()<=0){

			deleteNotify(schoolnotifykey);
			return ADD_NOTIFY_ERROR;
		}
		if(!addSchoolNotifyImage(schoolnotifykey,imagelist)){
			deleteNotify(schoolnotifykey);
			deleteNotifyImage(imagelist,imageurllist);
			return ADD_NOTIFY_ERROR;
		}
		return schoolnotifykey;
	}

	private void deleteNotifyContent(int schoolnotifykey) {
		// TODO Auto-generated method stub
		final String M  = "deleteNotifyContent********";
		pL(M);
	}
	private void deleteNotifyImage(List<Integer> imagelist,List<String> imageurllist) {
		// TODO Auto-generated method stub
		final String M  = "deleteNotifyImage********>>";
		pL(M);
		deleteNotifyImageFromSql(imagelist);
		deleteNotifyImageFromFile(imageurllist);
	}
	private void deleteNotifyImageFromFile(List<String> imageurllist) {
		// TODO Auto-generated method stub
		final String M  = "deleteNotifyImageFromFiles******>>";
		pL(M);
		for(String url:imageurllist){
			ImageUtil.deleteFileByGroupAndName(url);
		}
	}
	private void deleteNotifyImageFromSql(List<Integer> imagelist){
		final String M  = "deleteNotifyImageFromSql********>>";
		pL(M);
		for(Integer id:imagelist){
			Image image =new Image();
			image.setImageid(id);
			getImageModel().deleteById(image);
		}
	}
	private boolean addSchoolNotifyImage(int schoolnotifykey,
			List<Integer> imagelist) {
		// TODO Auto-generated method stub
		final String M  = "addSchoolNotifyImage******>>";
		pL(M);
		for(Integer imageid:imagelist){
			SchoolNotifyImage schoolnotifyimage = new SchoolNotifyImage();
			SchoolNotify schoolnotify = new SchoolNotify();
			schoolnotify.setSchoolnotifyid(schoolnotifykey);
			schoolnotifyimage.setSchoolnotify(schoolnotify);
			Image image = new Image();
			image.setImageid(imageid);
			if(imageid==-1){
				return false;
			}
			schoolnotifyimage.setImage(image);
			if(!getSchoolNotifyImageModel().putInfo(schoolnotifyimage)){
				return false;
			}
		}
		return true;
	}
	private void deleteNotify(int schoolnotifykey) {
		// TODO Auto-generated method stub
		final String M  = "deleteNotify**********>>";
		pL(M);
		getSchoolNotifyModel().deleteNotifyById(schoolnotifykey);
	}
	private List<Integer> addNotifyImage(
			TeacherAddNotifyReceive teacheraddnotifyreceive,List<String> imageurllist) {
		// TODO Auto-generated method stub
		final String M  = "addNotifyImage********>>";
		pL(M);
		return insertIntoImageTable(imageurllist);
	}
	private List<Integer> insertIntoImageTable(List<String> imageurllist) {
		// TODO Auto-generated method stub
		final String M  = "insertIntoImageTable******>>";
		pL(M);
		List<Integer> imageidlist = new ArrayList<Integer>();
		try{
			for(String imageurl:imageurllist){
				Image image = new Image();
				image.setImagename(imageurl);
				image.setImagesrc(imageurl);
				int imagekey = getImageModel().putInfoGetPrimaryKey(image);
				if(imagekey==-1){
					deleteNotifyImage(imageidlist,imageurllist);
					return null;
				}

				imageidlist.add(imagekey);
			}
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
		return imageidlist;
	}
	private List<String> generateImage(
			TeacherAddNotifyReceive teacheraddnotifyreceive) {
		// TODO Auto-generated method stub
		final String M  = "generateImgae******>>";
		pL(M);
		int index=0;
		List<String> imageurllist = new ArrayList<String>();
		for(PicUrl64 base64:teacheraddnotifyreceive.getPic_list()){
			index++;
			imageurllist.add(beginGenerateImage(base64.getPic_base64(),
					RandomUtil.getUUIDnumber()));
		}
		return imageurllist;
	}
	private String beginGenerateImage(String imagebase64,String titleplusindex){
		final String M  = "beginGenerateImage*****>>";
		pL(M);
		return ImageUtil.base64strToImage(imagebase64, "schoolnotify",titleplusindex+"");
	}
	/**
	 * 锟斤拷锟窖Ｍㄖ�

	 * @param teacheraddnotifyreceive
	 * @return
	 */
	private int addNotifyContent(
			TeacherAddNotifyReceive teacheraddnotifyreceive) {
		// TODO Auto-generated method stub
		final String M  = "addNotifyContent*******>>";
		pL(M);
        int maxid = getMaxIdOfNotifyOfDepartment(teacheraddnotifyreceive);
		int resultid = getCurrentMaxId(teacheraddnotifyreceive,maxid);
        if(maxid==0){
        	if(insertSchoolNotify(teacheraddnotifyreceive,resultid)){
        		return resultid;
        	}
        }else{
        	 if(updateSchoolNotify(teacheraddnotifyreceive,resultid)){
        		 return resultid;
        	 }
        }
        return -1;
	}
	private boolean updateSchoolNotify(TeacherAddNotifyReceive teacheraddnotifyreceive,
			int resultid) {
		// TODO Auto-generated method stub
		SchoolNotify schoolnotify = initSchoolNotify(teacheraddnotifyreceive, resultid);
		return getSchoolNotifyModel().updateSchoolNotify(schoolnotify,schoolnotify);
	}
	private boolean insertSchoolNotify(TeacherAddNotifyReceive teacheraddnotifyreceive,
			int resultid) {
		// TODO Auto-generated method stub
		try{
			SchoolNotify schoolnotify = initSchoolNotify(teacheraddnotifyreceive,resultid);
			return getSchoolNotifyModel().addSchoolNotifyKeyContent(schoolnotify);
		}catch(Exception e){
			e.printStackTrace();
		}	
		return false;
	
	}
	private SchoolNotify initSchoolNotify(
			TeacherAddNotifyReceive teacheraddnotifyreceive, int resultid) {
		SchoolNotify schoolnotify = new SchoolNotify();
		// TODO Auto-generated method stub
		schoolnotify.setSchoolnotifyid(resultid);
		schoolnotify.setTitle(teacheraddnotifyreceive.getTheme());
		schoolnotify.setPlace(teacheraddnotifyreceive.getPlace());
		schoolnotify.setStarttime(DateUtil.stringToDate(
				teacheraddnotifyreceive.getStarttime(),"yyyy-mm-dd"));
		schoolnotify.setEndtime(DateUtil.stringToDate(
				teacheraddnotifyreceive.getEndtime(),"yyyy-mm-dd"));
		schoolnotify.setRemindertime(DateUtil.stringToDate(
				teacheraddnotifyreceive.getAttion_time(),"yyyy-mm-dd"));
		schoolnotify.setContent(teacheraddnotifyreceive.getContent());
		Department department = new  Department();
		department.setDepartmentcode(teacheraddnotifyreceive.getDepartmentcode());
		schoolnotify.setDepartment(department);
		Teacher teacher = new Teacher();
		teacher.setTeachernumber(teacheraddnotifyreceive.getUser_number());
		schoolnotify.setTeacher(teacher);
		java.util.Date curDate = new java.util.Date();
		Timestamp d = new Timestamp(curDate.getTime());
		schoolnotify.setPublishtime(d);
		schoolnotify.setHitcount(0);
		return schoolnotify;
	}
	/**
	 *1:锟斤拷询锟斤拷锟斤拷应学校锟斤拷锟斤拷锟絠d
	 *    锟斤拷锟轿拷锟斤拷锟斤拷业锟斤拷锟角帮拷锟斤拷锟絠d锟斤拷锟斤拷锟斤拷锟斤拷十锟斤拷1锟斤拷锟斤拷
	 *    锟斤拷锟轿拷锟斤拷锟斤拷业锟斤拷锟叫Ｍㄖ拷锟斤拷锟斤拷id锟叫讹拷锟角凤拷锟斤拷为锟斤拷10锟斤拷
	 *    锟斤拷锟轿拷锟�0锟斤拷锟津将憋拷id锟斤拷锟斤拷为锟斤拷前id锟斤拷牡锟揭伙拷锟斤拷锟斤拷锟斤拷
	 *    锟斤拷10锟斤拷锟津将憋拷通知id锟斤拷锟斤拷为锟饺憋拷通知id锟斤拷1锟斤拷id
	 *2:为锟斤拷锟津将碉拷前通知锟斤拷id锟斤拷锟斤拷为锟角革拷锟斤拷锟斤拷锟矫碉拷前通知为锟斤拷锟斤拷通知
	 *    执锟叫诧拷锟斤拷
	 *3:锟斤拷为锟斤拷锟斤拷锟斤拷锟街革拷锟絠d锟斤拷锟斤拷学校通知
	 **/
	private int getCurrentMaxId(TeacherAddNotifyReceive teacheraddnotifyreceive
			,int maxid){

		if(ObjectUtil.isO(maxid)){
			maxid = whenCurrentIdOfDepartmentIsNull(teacheraddnotifyreceive);   
		}else{
			maxid = whenCurrentIdOfDepartmentIsNotNull(maxid);
		}
		return maxid;
	}

	private int whenCurrentIdOfDepartmentIsNull(TeacherAddNotifyReceive
			teacheraddnotifyreceive) {
		// TODO Auto-generated method stub
		//锟斤拷锟轿拷锟斤拷锟斤拷业锟斤拷锟角帮拷锟斤拷锟絠d锟斤拷锟斤拷锟斤拷锟斤拷十锟斤拷1锟斤拷锟斤拷
		int currentmaxid = getMaxIdOfNotify(teacheraddnotifyreceive);
		return DigitUtil.updateMaxIdWhenNull(currentmaxid);
	}
	private int whenCurrentIdOfDepartmentIsNotNull(int currentmaxid) {
		// TODO Auto-generated method stub
		return DigitUtil.updateMaxIdWhenNotNull(currentmaxid);
	}
	private void pL(String M){
		L.p(T+M);

	}
	public void querySchoolNotifyByPage(HttpServletRequest request,
			HttpServletResponse response,
			SchoolNotifyListReceive schoolnotifyreceive) {
		// TODO Auto-generated method stub
		switch (schoolnotifyreceive.getRole()){
		case Role.student:
			whenStudentQuery(request,response,schoolnotifyreceive);
			break;
		case Role.teacher:
			whenTeacherQuery(request,response,schoolnotifyreceive);
			break;
		default:
		}
	}
	private void whenTeacherQuery(HttpServletRequest request,
			HttpServletResponse response,
			SchoolNotifyListReceive schoolnotifyreceive) {
		// TODO Auto-generated method stub
		List<ReceiveSchoolNotify> receiveschoolnotifylist = 
				(List<ReceiveSchoolNotify>)getReceiveSchoolNotifyModel()
				.whenTeacherQuery(schoolnotifyreceive);
		List<SchoolNotify> schoolnotifylist = 
				getSchoolNotifyModel().queryByReceiveSchoolNotifys(receiveschoolnotifylist);
		sendListSuccess(getSuccessParam(request, response, schoolnotifylist,schoolnotifyreceive.getToken(),
				schoolnotifyreceive.getCode()));   
	}
	private void whenStudentQuery(HttpServletRequest request,
			HttpServletResponse response,
			SchoolNotifyListReceive schoolnotifyreceive) {
		// TODO Auto-generated method stub
		List<ReceiveSchoolNotify> receiveschoolnotifylist = 
				(List<ReceiveSchoolNotify>)getReceiveSchoolNotifyModel()
				.whenStudentQuery(schoolnotifyreceive);
		List<SchoolNotify> schoolnotifylist = getSchoolNotifyModel()
				.queryByReceiveSchoolNotifys(receiveschoolnotifylist);
		sendListSuccess(getSuccessParam(request, response, schoolnotifylist,schoolnotifyreceive.getToken(),
				schoolnotifyreceive.getCode()));  

	}
	public void querySchoolNotifyById(HttpServletRequest request,
			HttpServletResponse response,
			SchoolNotifyListDetailReceive schoolnotifyreceive) {
		// TODO Auto-generated method stub
		List<SchoolNotifyImage> schoolnotifyimagelist = getSchoolNotifyImageModel()
				.queryAllBySchoolNotifyId(schoolnotifyreceive
						.getSchoolnotifyid());
		sendSuccess(getSuccessParam(request, response, schoolnotifyimagelist,
				schoolnotifyreceive.getToken(),schoolnotifyreceive.getCode()));
		//		
		//          SchoolNotify schoolnotify = getSchoolNotifyModel().queryBySchoolNotifyId(schoolnotifyreceive
		//        		  .getSchoolnotifyid());
		//          if(ObjectUtil.isNull(schoolnotify)){
		////        	  sendFailure()
		//        	  return;
		//          }
		//          List<SchoolNotifyImage> schoolnotifyimagelist = getSchoolNotifyImageModel()
		//        		  .queryBySchoolNotifyId(schoolnotify.getSchoolnotifyid());
		//          
	}

	public void deleteSchoolNotify(HttpServletRequest request,
			HttpServletResponse response,
			DeleteSchoolNotifyReceive deleteschoolnotifyreceive) {
		// TODO Auto-generated method stub
		int schoolnotifyid = deleteschoolnotifyreceive.getSchoolnotifyid();
		List<SchoolNotifyImage> schoolnotifyimagelist = 
				querySchoolNotifyImageById(schoolnotifyid);
		deleteSchoolNotifyImageById(schoolnotifyid);
		deleteReceiveSchoolNotifyBySchoolNotifyId(schoolnotifyid);
		List<String> imageurllist = 
				queryImageUrlBySchoolNotifyImageList(schoolnotifyimagelist);
		deleteSchoolImageBySchoolNotifyImageList(schoolnotifyimagelist);
		deleteSchoolNotifyById(schoolnotifyid);

		deleteImageFileByUrlList(imageurllist);
		sendDeleteSuccess(getSuccessParam(request, response, "",deleteschoolnotifyreceive.getToken(),
				deleteschoolnotifyreceive.getCode()));
	}
	private boolean deleteReceiveSchoolNotifyBySchoolNotifyId(int schoolnotifyid) {
		// TODO Auto-generated method stub
		return getReceiveSchoolNotifyModel().deleteReceiveSchoolNotifyBySchoolNotifyid(
				schoolnotifyid);
	}
	private void deleteImageFileByUrlList(List<String> imageurllist) {
		// TODO Auto-generated method stub
		for(int i=0,len=imageurllist.size();i<len;i++){
			String imageurl = imageurllist.get(i);
			ImageUtil.deleteFileByGroupAndName(imageurl);
		}
	}
	private boolean deleteSchoolImageBySchoolNotifyImageList(
			List<SchoolNotifyImage> schoolnotifyimagelist) {
		// TODO Auto-generated method stub
		return getImageModel().deleteBySchoolNotifyImageList(schoolnotifyimagelist);
	}
	private List<String> queryImageUrlBySchoolNotifyImageList(
			List<SchoolNotifyImage> schoolnotifyimagelist) {
		// TODO Auto-generated method stub
		return getImageModel().queryAllBySchoolNotifyImage(schoolnotifyimagelist);
	}
	private boolean deleteSchoolNotifyById(int schoolnotifyid) {
		// TODO Auto-generated method stub
		return getSchoolNotifyModel().deleteNotifyById(schoolnotifyid);
	}
	private List<SchoolNotifyImage> querySchoolNotifyImageById(int schoolnotifyid){
		return getSchoolNotifyImageModel().queryBySchoolNotifyId(schoolnotifyid);
	}

	public void doSchoolNotifyFirst(HttpServletRequest request,
			HttpServletResponse response,
			SchoolNotifyFirstReceive schoolnotifyfirst) {
		// TODO Auto-generated method stub
		SchoolNotify schoolnotify = getReceiveSchoolNotifyModel().querySchoolNotifyFirst(schoolnotifyfirst);
		sendSchoolNotifyFirstSuccess(getSuccessParam(request, response,
				schoolnotify,"",schoolnotifyfirst.getCode()));
	}
	private boolean  deleteSchoolNotifyImageById(int id){
		return getSchoolNotifyImageModel().deleteBySchoolNotifyId(id);	
	}
	private void sendSuccess(SuccessParam successparam){
		getResponseService().doQuerySchoolNotifyDetail(successparam);
	}
	private void sendFailure(FailureParam failureparam){
		getResponseService().doQuerySchoolNotifyListFailure(failureparam);
	}
	private void sendListSuccess(SuccessParam successparam){
		getResponseService().doQuerySchoolNotifyList(successparam);
	}
	private void sendListFailure(FailureParam failureparam){
		getResponseService().doQuerySchoolNotifyListFailure(failureparam);
	}
	private void sendDeleteSuccess(SuccessParam successparam){
		getResponseService().doDeleteSchoolNotifySuccess(successparam);
	}
	private void sendDeleteFailure(FailureParam failureparam){
		getResponseService().doDeleteSchoolNotifyFailure(failureparam);
	}
	private void sendSchoolNotifyFirstSuccess(SuccessParam successparam){
		getResponseService().doSchoolNotifyFirst(successparam);
	}
}
